package com.hpp.web;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hpp.filter.utils.TokenUtil;
import com.hpp.model.SysUser;
import com.hpp.service.IUserService;
import com.hpp.utils.RespJson;
import com.hpp.utils.ResultCode;

@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
 
	@Autowired
	IUserService userService;
	
	@RequestMapping(value = {"","/","/index"})
	public String index(HttpSession session, Model model) {
		return "index";
	}
	
	/*@RequestMapping(value = {"","/","/index"})
	public void login(Model model,HttpServletRequest request,HttpServletResponse response) {
		try {
			String url = "http://" + request.getServerName() + ":" + request.getServerPort() + "/head/html/index.html";
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("跳转失败");
		}
	}*/
	 
	@ResponseBody
	@RequestMapping(value = "/logining", method = RequestMethod.POST)
	public RespJson logining(HttpSession session, HttpServletRequest request,
			@RequestParam(value = "userName", required = true) String name,
			@RequestParam(value = "password", required = true) String password, Model model) {
		logger.debug("into server login........");

		try {
			// 校验用户名和密码，校验失败，返回登录页面
			if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
				logger.debug("login failed........登录失败，用户名或者密码为空");
				return new RespJson(false, "用户不存在！", ResultCode.USER_NOT_EXIST, null);
			}
			return logining(session, request, name, password);
		} catch (Exception e) {
			logger.error("未知错误", e);
			return new RespJson(false, "未知错误,请联系管理员！", ResultCode.ERROR, null);
		}
	}
	
	private RespJson logining(HttpSession session, HttpServletRequest request, String name, String password)
			throws Exception {
		HashMap<String, Object> map = new HashMap<String,Object>();
		map.put("name", name);
		SysUser user = userService.getUserInfo(map);
		if (null == user) {
			logger.debug("login failed........登录失败，用户不存在");
			return new RespJson(false, "用户不存在", ResultCode.USER_NOT_EXIST, null);
		}
		if (user.getUserPwd().toLowerCase().equals(password.toLowerCase())) {
			HashMap<String, Object> result = new HashMap<String,Object>();
			String access_token = TokenUtil.generateToken(user.getId());
			session.setAttribute(access_token, user);
			result.put("access_token", access_token);
		    result.put("loginName", name);
			logger.debug("login successful........");
			return new RespJson(true, "登录成功", ResultCode.SUCCESS,result);
		} else {
			logger.debug("login failed........登录失败，账号密码错误");
			return new RespJson(false, "登录失败，账号密码错误", ResultCode.USER_NOT_EXIST, null);
		}
	}
	
	/**
	 * @param session
	 * @param request
	 * @return 退出
	 */
	@ResponseBody
	@RequestMapping(value = "/loginout", method = RequestMethod.POST)
	public RespJson loginOut(HttpSession session, HttpServletRequest request) {
		String token = request.getHeader("token");
		SysUser user = (SysUser)session.getAttribute(token);
		if (null != user) {
			session.removeAttribute(token);
			logger.debug("logout successfully.........退出成功");
		}
		return new RespJson(true, "退出成功", ResultCode.SUCCESS, null);
	}
	
	/**
	 * @Title checkToken  
	 * @Description 校验token存不存在
	 * @author hanpp
	 * @param request
	 * @param session
	 * @return RespJson
	 * @date 2019年1月19日 下午5:34:56  
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/token",method = RequestMethod.POST)
	public RespJson checkToken(HttpServletRequest request,HttpSession session){
		String token = request.getHeader("token");
		SysUser user = (SysUser)session.getAttribute(token);
		if (user == null) {
			return new RespJson(false, "token不存在，请重新登录", ResultCode.ERROR, "");
		} else {
			return new RespJson(true, "token存在", ResultCode.SUCCESS, "");
		}
	}
	
}
